package tmc.app.luckydraw;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.climaxi.core.ui.Loading;

import tmc.app.data.DBHandler;
import tmc.app.data.GlobalVariables;
import tmc.app.data.ObjRecordData;
import tmc.app.data.ObjUser;
import tmc.app.data.ProcessData;
import tmc.app.main.MainActivity;
import tmc.app.results.ActivityResult;

import android.R.integer;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class ActivityLuckyDraw  extends Activity{
    private Button btnPlay;
	public int mRotation = 0;
	public float mScale = 1.0f;
	public int mScaleNum = 0, mOffsetsNum;
	Timer t;
	TimerTask task;
	Timer t2;
	TimerTask task2;
	Timer t3;
	TimerTask task3;

	int time = 0;
	int time2 = 0;
	int time3 = 0;
	int degreeWin = -1;
	private Context mContext;
	private DBHandler db;
	private Activity mActivity;
	List<String> lstGiaiThuong = new ArrayList<String>();
	List<String> lstCountGiaiThuong = new ArrayList<String>();
	private String[] plantArray;
	private ImageView layout_touch_beer;
	private int count = 0;
	private boolean isStart = false;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_luckydraw);
        mContext = this;
        mActivity = this;
        initLayout();
        initEvents();
        //setCountGlobal();
        checkEmptyPrize();
        //degreeWin = returnDegreeWin(randomWinFromPercent(Integer.parseInt(GlobalVariables.defaultRecordData.getPercent()), GlobalVariables.defaultRecordData));
    }

	public void setCountGlobal()
	{
		//GlobalVariables.globalCount = GlobalVariables.globalCount + GlobalVariables.count;
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    public void onBackPressed() {};
 
    public void initLayout()
    {

		db = new DBHandler(mContext);

		plantArray = mActivity.getResources().getStringArray(
				R.array.list_giaithuong);
//    	btnPlay = (Button)findViewById(R.id.btn_play);
		StarshipView sv = (StarshipView) findViewById(R.id.ship1);
		if (sv != null) {
			sv.setBitmapFromResource(R.drawable.img_wheel);
			sv.setScale(1.0f);
			sv.invalidate();
		}
		
		layout_touch_beer = (ImageView)findViewById(R.id.layout_touch_beer);
    }
    
    public void initEvents()
    {
    	layout_touch_beer.setOnClickListener(onClickListener);
    	/*try {
        	startWheel();
		} catch (Exception e) {
			// TODO: handle exception
		}*/
    }
    
    public void startWheel()
    {
		StarshipView sv = (StarshipView) findViewById(R.id.ship1);

		float newScale1 = 1.0f;
		float newOffset1 = 0f;
		int degrees1 = (sv == null) ? 0 : sv.getDegrees();
		newScale1 = (sv == null) ? 1f : sv.getScale();
		newOffset1 = (sv == null) ? 1f : sv.getOffsetX();
		
		if (sv != null) {
			sv.setScale(newScale1);
			startTimer(sv);
		}
    }
    
    public void setClickableOnBeer(int type)
    {
    	switch (type) {
		case 0:
			layout_touch_beer.setClickable(false);
			break;
		case 1:
			layout_touch_beer.setClickable(true);
			break;
		default:
			break;
		}
    }
    
    public OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			/*StarshipView sv = (StarshipView) findViewById(R.id.ship1);

			float newScale1 = 1.0f, newScale2 = 1.0f;
			float newOffset1 = 0f, newOffset2 = 0f;
			int degrees1 = (sv == null) ? 0 : sv.getDegrees();
			newScale1 = (sv == null) ? 1f : sv.getScale();
			newOffset1 = (sv == null) ? 1f : sv.getOffsetX();
			
			if (sv != null) {
				sv.setScale(newScale1);
				startTimer(sv);
			}*/
			isStart = true;
			if(isStart != GlobalVariables.isStartWheel)
			{
				GlobalVariables.isStartWheel = true;
			}else{
				GlobalVariables.isStartWheel = false;
			}
			try {
				if(GlobalVariables.isStartWheel)
				{
		        	startWheel();
				}else{
					StarshipView sv = (StarshipView) findViewById(R.id.ship1);

					float newScale1 = 1.0f, newScale2 = 1.0f;
					float newOffset1 = 0f, newOffset2 = 0f;
					int degrees1 = (sv == null) ? 0 : sv.getDegrees();
					newScale1 = (sv == null) ? 1f : sv.getScale();
					newOffset1 = (sv == null) ? 1f : sv.getOffsetX();
					
					stopTimer1();
					sv.setDegrees(0);
					if(degreeWin != -1)
					{
						startTimer2(degreeWin, sv);
						setClickableOnBeer(0);
						GlobalVariables.isStartWheel = false;
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	};

	public void startTimer(final StarshipView sv) {

		t = new Timer();
		task = new TimerTask() {

			@Override
			public void run() {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
//						Log.v("TEST", "time: " + time);
						if (time > -1)
						{
							time = time + 40;
							sv.setDegrees(time);
							sv.invalidate();
						}
						else {
							if(t != null)
							{
								t.cancel();
								t = null;
								sv.setDegrees(1800);
								if(degreeWin != -1)
								{
									startTimer2(degreeWin, sv);
								}
							}
						}
					}
				});
			}
		};
		t.scheduleAtFixedRate(task, 1000, 100);
	}
	
	public void stopTimer1()
	{
		if(t != null)
		{
			t.cancel();
			t = null;
		}
	}
	
	public void updateDb(ObjRecordData data)
	{
		db.updateRecordData(data);
		GlobalVariables.lstData.clear();
		GlobalVariables.lstData = db.getAllItemsRecordData();
	}
	
	public int randomWinFromPercent(int percent,ObjRecordData data)
	{
		Random r = new Random();
		int results = -1;
		int i1 = r.nextInt(100 - 0) + 0;
		if(i1 > percent)
		{
			results = 0;
			GlobalVariables.result = "0";
		}
		else
		{
			Random r2 = new Random();
			int i2 = r2.nextInt(6 - 1) + 1;
			
			switch (i2) {
			case 1:
				if(Integer.parseInt(data.getDataAo()) > Integer.parseInt(data.getResultAo()))
				{
					results = 1;
					GlobalVariables.result = "1";
					data.setResultAo(String.valueOf(Integer.parseInt(data.getResultAo())+1));
					updateDb(data);
				}
				else{
					GlobalVariables.result = "0";
					results = randomWinFromPercent(percent, data);
				}
				break;
			case 2:
				if(Integer.parseInt(data.getDataBalo()) > Integer.parseInt(data.getResultBalo()))
				{
					results = 2;
					GlobalVariables.result = "2";
					data.setResultBalo(String.valueOf(Integer.parseInt(data.getResultBalo())+1));
					updateDb(data);
				}else{
					GlobalVariables.result = "0";
					results = randomWinFromPercent(percent, data);
				}
				break;
			case 3:
				if(Integer.parseInt(data.getDataSotay()) > Integer.parseInt(data.getResultSotay()))
				{
					results = 3;
					GlobalVariables.result = "3";
					data.setResultSotay(String.valueOf(Integer.parseInt(data.getResultSotay())+1));
					updateDb(data);
				}else{
					GlobalVariables.result = "0";
					results = randomWinFromPercent(percent, data);
				}
				break;
			case 4:
				if(Integer.parseInt(data.getDataBut()) > Integer.parseInt(data.getResultBut()))
				{
					results = 4;
					GlobalVariables.result = "4";
					data.setResultBut(String.valueOf(Integer.parseInt(data.getResultBut())+1));
					updateDb(data);
				}else{
					GlobalVariables.result = "0";
					results = randomWinFromPercent(percent, data);
				}
				break;
			case 5:
				if(Integer.parseInt(data.getDataMockhoa()) > Integer.parseInt(data.getResultMockhoa()))
				{
					results = 5;
					GlobalVariables.result = "5";
					data.setResultMockhoa(String.valueOf(Integer.parseInt(data.getResultMockhoa())+1));
					updateDb(data);
				}else{
					GlobalVariables.result = "0";
					results = randomWinFromPercent(percent, data);
				}
				break;
				
			default:
				break;
			}
		}
		
		return results;
	}
	
	public int returnDegreeWin(int i)
	{
		int degree = -1;
		//0: ko trung, 1:ao, 2: balo, 3: sotay, 4:but, 5:mockhoa
		switch (i) {
		case 0:
			degree = randomLosePosition();
			break;
		case 1:
			degree = 144;
			break;
		case 2:
			degree = 216;
			break;
		case 3:
			degree = 72;
			break;
		case 4:
			degree = 0;
			break;
		case 5:
			degree = 288;
			break;
		default:
			break;
		}
		
		return degree;
	}
	
	public int randomLosePosition()
	{
		Random r = new Random();
		int degreeLos = -1;
		//o->4
		int i1 = r.nextInt(5 - 0) + 0;
		switch (i1) {
		case 0:
			degreeLos = 36;
			break;
		case 1:
			degreeLos = 108;
			break;
		case 2:
			degreeLos = 180;
			break;
		case 3:
			degreeLos = 252;
			break;
		case 4:
			degreeLos = 324;
			break;
		default:
			break;
		}
		
		return degreeLos;
	}
	
	public void resetGiaithuong()
	{
		GlobalVariables.globalCount = 0;
		Log.v("TEST","AO " + GlobalVariables.defaultRecordData.getDataAo());
		Log.v("TEST","AO loadCountGiaiThuong " + GlobalVariables.loadCountGiaiThuong(mActivity, GlobalVariables.AO));
		GlobalVariables.defaultRecordData.setDataAo(String.valueOf(Integer.parseInt(GlobalVariables.defaultRecordData.getDataAo()) + GlobalVariables.loadCountGiaiThuong(mActivity, GlobalVariables.AO)));
		GlobalVariables.defaultRecordData.setDataBalo(String.valueOf(Integer.parseInt(GlobalVariables.defaultRecordData.getDataBalo()) + GlobalVariables.loadCountGiaiThuong(mActivity, GlobalVariables.BALO)));
		GlobalVariables.defaultRecordData.setDataSotay(String.valueOf(Integer.parseInt(GlobalVariables.defaultRecordData.getDataSotay()) + GlobalVariables.loadCountGiaiThuong(mActivity, GlobalVariables.SO_TAY)));
		GlobalVariables.defaultRecordData.setDataBut(String.valueOf(Integer.parseInt(GlobalVariables.defaultRecordData.getDataBut()) + GlobalVariables.loadCountGiaiThuong(mActivity, GlobalVariables.VIET)));
		GlobalVariables.defaultRecordData.setDataMockhoa(String.valueOf(Integer.parseInt(GlobalVariables.defaultRecordData.getDataMockhoa()) + GlobalVariables.loadCountGiaiThuong(mActivity, GlobalVariables.MOC_KHOA)));
		
		db.updateRecordData(GlobalVariables.defaultRecordData);
	}
	
	public void checkEmptyPrize()
	{
		
		int countTotalLuotQuay = 30;
		int countLimitLuotQuay = 15;
		
		//int countTotalLuotQuay = 15;
		//int countLimitLuotQuay = 6;
		
		if(GlobalVariables.globalCount < countLimitLuotQuay)
		{
			Log.v("TEST","count < 20");
			degreeWin = returnDegreeWin(randomWinFromPercent(Integer.parseInt(GlobalVariables.defaultRecordData.getPercent()), GlobalVariables.defaultRecordData));
		}
		else
		{
			if((Integer.parseInt(GlobalVariables.defaultRecordData.getResultAo()) < Integer.parseInt(GlobalVariables.defaultRecordData.getDataAo()) ||
					Integer.parseInt(GlobalVariables.defaultRecordData.getResultBalo()) < Integer.parseInt(GlobalVariables.defaultRecordData.getDataBalo()) ||
					Integer.parseInt(GlobalVariables.defaultRecordData.getResultBut()) < Integer.parseInt(GlobalVariables.defaultRecordData.getDataBut()) ||
					Integer.parseInt(GlobalVariables.defaultRecordData.getResultSotay()) < Integer.parseInt(GlobalVariables.defaultRecordData.getDataSotay()) ||
					Integer.parseInt(GlobalVariables.defaultRecordData.getResultMockhoa()) < Integer.parseInt(GlobalVariables.defaultRecordData.getDataMockhoa())))
			{
				Log.v("TEST","count > 20 va con giai thuong");
				degreeWin = returnDegreeWin(randomWinFromPercent(100, GlobalVariables.defaultRecordData));
			}
			else
			{
				degreeWin = returnDegreeWin(randomWinFromPercent(0, GlobalVariables.defaultRecordData));
			}
		}
		
		if(GlobalVariables.globalCount == countTotalLuotQuay)
		{
			resetGiaithuong();
		}
		else
		{
			GlobalVariables.globalCount++;
		}
	}
	
	public void startTimer2(final int degree, final StarshipView sv) {

		t2 = new Timer();
		task2 = new TimerTask() {

			@Override
			public void run() {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						//cac goc trung 0, 72, 144, 216, 288
//						Log.v("TEST", "time2: " + time2);
						if (time2 < 720-(180+degree+(36/2)))
						{
							time2 = time2 + 10;
							sv.setDegrees(time2);
							sv.invalidate();
						}
						else {
							if(t2 != null)
							{
								t2.cancel();
								t2 = null;
								startTimer3(degree, sv);
							}
						}
					}
				});
			}
		};
		t2.scheduleAtFixedRate(task2, 0, 100);
	}
	
	public void startTimer3(final int degree, final StarshipView sv) {

		t3 = new Timer();
		task3 = new TimerTask() {

			@Override
			public void run() {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						if (time3 < 2)
						{
							time3 = time3 + 1;
						}
						else {
							if(t3 != null)
							{
								t3.cancel();
								t3 = null;
								time3 = 0;
								
								insertRecordUser();
								if(GlobalVariables.lanthu != 0)
								{
									GlobalVariables.lanthu--;
								}
								showDialogLoading(mActivity, sv);
							}
						}
					}
				});
			}
		};
		t3.scheduleAtFixedRate(task3, 0, 2000);
	}
	
	public void resetWheel(StarshipView sv)
	{
		try {
			time = 0;
			time2 = 0;
			setClickableOnBeer(1);
			checkEmptyPrize();
			//degreeWin = returnDegreeWin(randomWinFromPercent(Integer.parseInt(GlobalVariables.defaultRecordData.getPercent()), GlobalVariables.defaultRecordData));
//			sv.setDegrees(0);
//			startWheel();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public String getCurrentDate()
	{
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = df.format(Calendar.getInstance().getTime());
		Log.v("TEST", "date " + date);
		return date;
	}
	
	public void insertRecordUser()
	{
		if(GlobalVariables.result.equals("0"))
		{
			Log.v("TEST", "insert not");
			ObjUser data = new ObjUser(getCurrentDate(), GlobalVariables.tenquan, GlobalVariables.phone, String.valueOf(GlobalVariables.count), "0", "0",GlobalVariables.hoten);
			db.insertItemsRecordUser(data);
		}else{
			Log.v("TEST", "insert yes");
			if(lstGiaiThuong.size() != 0)
			{
				if(!checkTrung(plantArray[Integer.parseInt(GlobalVariables.result)-1], lstGiaiThuong))
				{
					lstGiaiThuong.add(plantArray[Integer.parseInt(GlobalVariables.result)-1]);
				}
				
				lstCountGiaiThuong.add(plantArray[Integer.parseInt(GlobalVariables.result)-1]);
			}else{
				lstGiaiThuong.add(plantArray[Integer.parseInt(GlobalVariables.result)-1]);
				lstCountGiaiThuong.add(plantArray[Integer.parseInt(GlobalVariables.result)-1]);
			}
			ObjUser data = new ObjUser(getCurrentDate(), GlobalVariables.tenquan, GlobalVariables.phone, String.valueOf(GlobalVariables.count), "1", GlobalVariables.result,GlobalVariables.hoten);
			db.insertItemsRecordUser(data);
		}
	}
	
	public boolean checkTrung(String txt,List<String> lst)
	{
		boolean isFound = false;
		for(int i = 0; i < lst.size(); i++)
		{
			if(lst.get(i).toString().equals(txt))
			{
				isFound = true;
				break;
			}
		}
		
		return isFound;
	}
	
	public int returnTrung(String txt, List<String> lst)
	{
		int count = 0;
		for(int i = 0; i < lst.size(); i++)
		{
			if(lst.get(i).toString().equals(txt))
			{
				count++;
			}
		}
		
		return count;
	}
	
	public void showDialogLoading(final Activity mActivity,final StarshipView sv) {
		final Dialog dialog = new Dialog(mContext, android.R.style.Theme_Black);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.activity_result);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.bg_transparent);
    	
		ImageView txt_title = (ImageView)dialog.findViewById(R.id.txt_title);
    	TextView txt_result = (TextView)dialog.findViewById(R.id.txt_result);
    	ImageView img_play = (ImageView)dialog.findViewById(R.id.img_play);
    	checkResult(txt_title,plantArray,txt_result);
    	setEmptyCount(img_play,txt_result);
    	img_play.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			ProcessData.ringPhone(mActivity);
				if (GlobalVariables.lanthu != 0) {
					resetWheel(sv);
					dialog.dismiss();
				} else {
					resetData();
					moveToHome();
					dialog.dismiss();
				}
			}
		});
    	
    	dialog.setCancelable(false);
    	dialog.show();
	}
	
	public void resetData()
	{
		GlobalVariables.result = null;
		GlobalVariables.hoten = null;
		GlobalVariables.phone = null;
		GlobalVariables.count = 0;
		GlobalVariables.lanthu = 0;
	}
	
	public void checkResult(ImageView txt_title,String[] plantArray,TextView txt_result)
	{
		if(GlobalVariables.result.equals("0"))
		{
	        setTextLoseDesc(txt_result,GlobalVariables.lanthu);
	        txt_title.setBackgroundResource(R.drawable.txt_close);
		}else{
	        txt_title.setBackgroundResource(R.drawable.txt_win);
			setTextWinDesc(txt_result,plantArray[Integer.parseInt(GlobalVariables.result)-1], GlobalVariables.lanthu);
		}
	}
	
    public void initEventsResults(ImageView img_play)
    {
    	img_play.setOnClickListener(onClickListener);
    }
    
    public void setEmptyCount(ImageView img_play,TextView txt_result)
    {
    	if(GlobalVariables.lanthu != 0)
    	{
        	img_play.setBackgroundResource(R.drawable.btn_quaytiep);
    	}else{
    		setTextHetLuotQuay(txt_result);
        	img_play.setBackgroundResource(R.drawable.btn_home_fail);
    	}
    }
    
    public void setTextWinDesc(TextView txt_result,String txt,int count)
    {
    	txt_result.setText(getResources().getString(R.string.txt_win1)+" "+txt+" "+getResources().getString(R.string.txt_win2)+"\n"+getResources().getString(R.string.txt_numberquay1)+ " "+String.valueOf(count)+" "+getResources().getString(R.string.txt_numberquay2));
    }
    
    public void setTextLoseDesc(TextView txt_result,int count)
    {
    	txt_result.setText(getResources().getString(R.string.txt_lose1)+"\n"+getResources().getString(R.string.txt_numberquay1)+ " "+String.valueOf(count)+" "+getResources().getString(R.string.txt_numberquay2));
    }
    
    public void setTextHetLuotQuay(TextView txt_result)
    {
    	String text = "";
    	if(lstGiaiThuong.size() != 0)
    	{
    		for(int i = 0 ; i < lstGiaiThuong.size(); i++)
    		{
    			if(i == lstGiaiThuong.size()-1)
    			{
            		text = text + " " + String.valueOf(returnTrung(lstGiaiThuong.get(i).toString(), lstCountGiaiThuong)) + " " +lstGiaiThuong.get(i).toString() + " .";
    			}else{
            		text = text + " " + String.valueOf(returnTrung(lstGiaiThuong.get(i).toString(), lstCountGiaiThuong)) + " " +lstGiaiThuong.get(i).toString() + " , ";
    			}
    		}
        	txt_result.setText(getResources().getString(R.string.txt_hetluotquay)+"\n"+ " "+text);
    	}else{
        	txt_result.setText(getResources().getString(R.string.txt_hetluotquay2)+"\n"+ " "+text);
    	}
    }
    
    public void moveToPlay()
    {
    	Intent intent = new Intent(this, ActivityLuckyDraw.class);
    	startActivity(intent);
		overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    	finish();
    }
    
    public void moveToHome()
    {
    	Intent intent = new Intent(this, MainActivity.class);
    	startActivity(intent);
		overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    	finish();
    }

	private class IntentLauncher extends Thread {
		private StarshipView sv;
		public IntentLauncher(StarshipView sv)
		{
			this.sv = sv;
		}
		
		public void run() {
			try {
				// Sleeping
				Thread.sleep(2000);
			} catch (Exception e) {
				// Log.e(TAG, e.getMessage());
			}
			// Start main activity
		}

	}
}
